<template>
  <div class="menu-management">
    <h2>{{ $t('message.menuManagement') }}</h2>
    
    <div class="menu-actions">
      <el-button type="primary" @click="openAddMenuDialog">{{ $t('message.addMenu') }}</el-button>
    </div>
    
    <el-table
      :data="menus"
      style="width: 100%"
      row-key="menuId"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="menuName" :label="$t('message.menuName')" width="200" align="left" header-align="left" />
      <el-table-column prop="menuIcon" :label="$t('message.menuIcon')" width="120" align="left" header-align="left">
        <template #default="scope">
          <i :class="scope.row.menuIcon"></i> {{ scope.row.menuIcon }}
        </template>
      </el-table-column>
      <el-table-column prop="menuUrl" :label="$t('message.menuUrl')" width="200" align="left" header-align="left" />
      <el-table-column prop="sortOrder" :label="$t('message.sortOrder')" width="100" align="left" header-align="left" />
      <el-table-column :label="$t('message.actions')" width="200" align="left" header-align="left">
        <template #default="scope">
          <el-button size="small" @click="editMenu(scope.row)">{{ $t('message.edit') }}</el-button>
          <el-button size="small" type="danger" @click="deleteMenu(scope.row.menuId)">{{ $t('message.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加/编辑菜单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="menuForm" :rules="menuRules" ref="menuFormRef" label-width="100px">
        <el-form-item :label="$t('message.menuName')" prop="menuName">
          <el-input v-model="menuForm.menuName"></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.menuIcon')" prop="menuIcon">
          <el-input v-model="menuForm.menuIcon"></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.menuUrl')" prop="menuUrl">
          <el-input v-model="menuForm.menuUrl"></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.parentMenu')" prop="parentId">
          <el-select v-model="menuForm.parentId" :placeholder="$t('message.selectParentMenu')">
            <el-option
              v-for="item in parentMenus"
              :key="item.menuId"
              :label="item.menuName"
              :value="item.menuId"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.sortOrder')" prop="sortOrder">
          <el-input-number v-model="menuForm.sortOrder" :min="0" :max="999"></el-input-number>
        </el-form-item>
        <el-form-item :label="$t('message.isActive')" prop="isActive">
          <el-switch v-model="menuForm.isActive"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t('message.cancel') }}</el-button>
          <el-button type="primary" @click="saveMenu">{{ $t('message.confirm') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores/auth';

export default {
  name: 'MenuManagement',
  setup() {
    const { t } = useI18n();
    const authStore = useAuthStore();
    
    // 菜单数据
    const menus = ref([]);
    const parentMenus = ref([]); // 用于父级菜单选择
    
    // 对话框相关
    const dialogVisible = ref(false);
    const dialogTitle = ref('');
    const isEdit = ref(false);
    
    // 表单数据
    const menuForm = ref({
      menuId: '',
      menuName: '',
      menuIcon: '',
      menuUrl: '',
      parentId: null,
      sortOrder: 0,
      isActive: true
    });
    
    const menuFormRef = ref();
    
    // 表单验证规则
    const menuRules = {
      menuName: [
        { required: true, message: t('message.pleaseEnterMenuName'), trigger: 'blur' }
      ],
      menuUrl: [
        { required: true, message: t('message.pleaseEnterMenuUrl'), trigger: 'blur' }
      ]
    };
    
    // 获取菜单列表
    const loadMenus = async () => {
      try {
        // 从API获取菜单数据
        const response = await fetch('/api/admin/menus', {
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          const data = await response.json();
          // 将扁平数据转换为树形结构
          menus.value = buildMenuTree(data);
          parentMenus.value = [{ menuId: null, menuName: t('message.noParentMenu') }, ...data];
        } else {
          ElMessage.error(t('message.failedToLoadMenus'));
        }
      } catch (error) {
        console.error('Error loading menus:', error);
        ElMessage.error(t('message.failedToLoadMenus'));
      }
    };
    
    // 构建菜单树
    const buildMenuTree = (menuList) => {
      const map = {};
      const roots = [];
      
      // 创建映射
      menuList.forEach(menu => {
        menu.children = [];
        map[menu.menuId] = menu;
      });
      
      // 构建树
      menuList.forEach(menu => {
        if (menu.parentId) {
          const parent = map[menu.parentId];
          if (parent) {
            parent.children.push(menu);
          } else {
            roots.push(menu);
          }
        } else {
          roots.push(menu);
        }
      });
      
      return roots;
    };
    
    // 打开添加菜单对话框
    const openAddMenuDialog = () => {
      isEdit.value = false;
      dialogTitle.value = t('message.addMenu');
      resetForm();
      dialogVisible.value = true;
    };
    
    // 编辑菜单
    const editMenu = (menu) => {
      isEdit.value = true;
      dialogTitle.value = t('message.editMenu');
      // 复制菜单数据到表单
      Object.assign(menuForm.value, menu);
      dialogVisible.value = true;
    };
    
    // 删除菜单
    const deleteMenu = async (menuId) => {
      try {
        await ElMessageBox.confirm(
          t('message.confirmDeleteMenu'),
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        const response = await fetch(`/api/admin/menus/${menuId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          ElMessage.success(t('message.deleteMenuSuccess'));
          loadMenus(); // 重新加载菜单
        } else {
          ElMessage.error(t('message.deleteMenuFailed'));
        }
      } catch (error) {
        console.error('Error deleting menu:', error);
      }
    };
    
    // 保存菜单
    const saveMenu = async () => {
      try {
        await menuFormRef.value.validate();
        
        let response;
        if (isEdit.value) {
          // 更新菜单
          response = await fetch(`/api/admin/menus/${menuForm.value.menuId}`, {
            method: 'PUT',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(menuForm.value)
          });
        } else {
          // 创建菜单
          response = await fetch('/api/admin/menus', {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(menuForm.value)
          });
        }
        
        if (response.ok) {
          ElMessage.success(isEdit.value ? t('message.updateMenuSuccess') : t('message.addMenuSuccess'));
          dialogVisible.value = false;
          loadMenus(); // 重新加载菜单
        } else {
          const errorData = await response.json();
          ElMessage.error(errorData.message || (isEdit.value ? t('message.updateMenuFailed') : t('message.addMenuFailed')));
        }
      } catch (error) {
        console.error('Error saving menu:', error);
        ElMessage.error(isEdit.value ? t('message.updateMenuFailed') : t('message.addMenuFailed'));
      }
    };
    
    // 重置表单
    const resetForm = () => {
      menuForm.value = {
        menuId: '',
        menuName: '',
        menuIcon: '',
        menuUrl: '',
        parentId: null,
        sortOrder: 0,
        isActive: true
      };
    };
    
    onMounted(() => {
      loadMenus();
    });
    
    return {
      menus,
      parentMenus,
      dialogVisible,
      dialogTitle,
      menuForm,
      menuFormRef,
      menuRules,
      openAddMenuDialog,
      editMenu,
      deleteMenu,
      saveMenu
    };
  }
};
</script>

<style scoped>
.menu-management {
  padding: 20px;
}

.menu-actions {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>